<?php
Yii::import('ext.wideImage.WideImage');

class DProductShop extends DActiveRecord {

    private $curPage = 0;
    private $defaultSort;
    public $params;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function init() {
        parent::init();
        
        //set params
        $this->params = Yii::app()->params['product_shop'];
    }

    public function tableName() {
        return 'product_shop';
    }

    public function rules() {
        return array(
            array('type_id, title, code', 'required'),
            array('activated_flag, hot', 'boolean'),
            array('title, code, keyword, description', 'length', 'max' => 255),
            array('file_download', 'validateFile'),
            array('id, short_content, detailed_content, folder_id, counter,'
                . 'title_seo, images, price, promotional_price',
                'safe'),
            array('type_id', 'numerical', 'integerOnly'=>true),
            array('id, title, code', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'rtype' => array(self::BELONGS_TO, 'NewsletterType', 'type_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
			'title' => 'Title',
			'code' => 'Code',
			'price' => 'Price',
			'promotional_price' => 'Sale off',
			'short_content' => 'Summary',
			'detailed_content' => 'Content',
			'counter' => 'Counter',
			'status' => 'Status',
			'hot' => 'Hot',
			'activated_flag' => 'Active',
			'images' => 'Images',
			'file_download' => 'File Download',
			'type_id' => 'Category',
		);
    }

    public function search() {
        //Restore state from session
        $this->restoreState();

        //Criteria
        $criteria       = new CDbCriteria;
        $this->setTableAlias('T');
        $criteria->with = array('rtype');

        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('T.title', $this->title, true);
        $criteria->compare('T.code', $this->code, true);
        $criteria->compare('T.activated_flag', $this->activated_flag);
        $criteria->compare('rtype.activated_flag', true);

        //Sorting
        $sort               = new CSort();
        $sort->defaultOrder = ($this->defaultSort == '') ? array('sort_order' => true) : $this->defaultSort;
        $sort->attributes = array(
            'title' => array(
                'asc'     => 'T.title ASC, T.sort_order DESC',
                'desc'    => 'T.title DESC, T.sort_order DESC',
                'default' => 'asc',
            ),
            'code' => array(
                'asc'     => 'T.code ASC, T.sort_order DESC',
                'desc'    => 'T.code DESC, T.sort_order DESC',
                'default' => 'asc',
            ),
            'price' => array(
                'asc'     => 'T.price ASC, T.sort_order DESC',
                'desc'    => 'T.price DESC, T.sort_order DESC',
                'default' => 'asc',
            ),
            'promotional_price' => array(
                'asc'     => 'T.promotional_price ASC, T.sort_order DESC',
                'desc'    => 'T.promotional_price DESC, T.sort_order DESC',
                'default' => 'asc',
            ),
            'type_id' => array(
                'asc'            => 'rtype.title ASC, T.sort_order DESC',
                'desc'           => 'rtype.title DESC, T.sort_order DESC',
                'default'        => 'asc',
            ),
            'activated_flag' => array(
                'asc'        => 'T.activated_flag ASC, T.sort_order DESC',
                'desc'       => 'T.activated_flag DESC, T.sort_order DESC',
                'default'    => 'asc',
            ),
            'hot' => array(
                'asc'        => 'T.hot ASC, T.sort_order DESC',
                'desc'       => 'T.hot DESC, T.sort_order DESC',
                'default'    => 'asc',
            ),
            'sort_order' => array(
                'asc'  => 'T.sort_order ASC',
                'desc' => 'T.sort_order DESC',
            ),
        );
        $sort->applyOrder($criteria);

        return new CActiveDataProvider($this, array(
                'criteria'   => $criteria,
                'sort'       => $sort,
                'pagination' => array('currentPage' => $this->curPage),
            ));
    }

    private function restoreState() {
        $state = SpsState::getState();

        if ($state) {
            if (isset($state['sort']))
                $this->defaultSort = $state['sort'];
            if (isset($state['page']))
                $this->curPage     = $state['page'];

            if (isset($state['search'])) {
                foreach ($state['search'] as $key => $value)
                    if ($value != '')
                        $this->$key = $value;
            }
        }
    }

    /**
     * Before save
     */
    protected function beforeSave() {
        parent::beforeSave();
        $this->setDefaultValue();

        return true;
    }

    protected function beforeDelete() {
        parent::beforeDelete();

        if (! empty($this->folder_id)) {
            $this->deleteFolderID($this->folder_id);
        }

        return true;
    }

    /**
     * Update user/time Sets
     */
    private function setDefaultValue() {
        if ($this->getIsNewRecord()) {
            $this->setAttribute('sort_order', $this->getAutoIncrement($this->tableName()));
        }
        //title_seo
        $this->setAttribute('title_seo', $this->getTitleSeo());
        
        //images
        if ( ! empty($this->images) ) {
            $images = explode(';', $this->images);
            $aTempo = array();
            
            foreach ($images as $value) {
                $pos = strrpos($value, '/') + 1;
                array_push($aTempo, substr($value, $pos));
            }
            $this->setAttribute('images', implode(';', $aTempo));
        } else {
            $this->images = null;
        }
        
        //file_download
        if ( ! empty($this->file_download) ) {
            $pos = strrpos($this->file_download, '/');
            if ( $pos ) {
                $sTempo = substr($this->file_download, $pos + 1);
                $this->setAttribute('file_download', $sTempo);
            }
        }
        
        //price
        $this->price = str_replace(',', '', $this->price);
        $this->promotional_price = str_replace(',', '', $this->promotional_price);
        
        return true;
    }

    private function getTitleSeo($title = '') {
        if (empty($title))
            $title = $this->title;

        $myhelpers = new MyHelpers();
        return $myhelpers->convertSeoStr($title);
    }

    /*-------------------------------------------------------------------------
     PROCESSING FILE
     ------------------------------------------------------------------------*/
    public function validateFile($attribute, $params) {
        $file = CUploadedFile::getInstance($this, $attribute);
        
        if ($file && !$this->hasErrors()) {//file is uploaded
            $aValid = array('jpg', 'png', 'gif');
            if (in_array($file->getExtensionName(), $aValid)) {
                $this->uploadFile($file, $attribute);
            } else {
                $this->addError($attribute, 'Please upload file: *.jpg, *.png, *.gif');
            }
        } else {
            if ($this->getScenario() == 'update' && isset($_POST['uploadedFileFlag'])) {
                if (isset($_POST['deleteFileFlag'])) {
                    $this->deleteFile($_POST['uploadedFileFlag']);
                    $this->file = null;
                }
                else
                    $this->file = $_POST['uploadedFileFlag'];
            }
        }
    }

    /**
     * Upload file to server and set file attribute.
     * @param CUPloadedFile $file
     */
    private function uploadFile($file, $attribute) {
        $uploadDir = $this->params['thumb_dir'];

        if ($this->getScenario() == 'insert') {
            $fileName = $this->getAutoIncrement($this->tableName()) . '.' . $file->getExtensionName();
        } elseif ($this->getScenario() == 'update') {
            if (isset($_POST['uploadedFileFlag'])) //delete old file
                $this->deleteFile($_POST['uploadedFileFlag']);

            $fileName = $this->id . '.' . $file->getExtensionName();
        }

        $path = $uploadDir . $fileName;
        if ($file->saveAs($path)) { //save to server
            $this->setAttribute($attribute, $fileName);
            
            //resize image
            if ($this->getAttribute('type_id') != 1) {
                $imageObj = WideImage::load($path);
                $imageObj->resizeDown(
                    $this->params['thumb_width'], $this->params['thumb_height'])
                ->saveToFile($path);
            }
            
            return true;
        } else {
            $this->addError($attribute, $file->getError());
            return false;
        }
    }

    private function deleteFile($fileName) {
        $path = $this->params['thumb_dir'] . $fileName;
        if (is_file($path)) {
            unlink($path);
            return TRUE;
        } else {
            return FALSE;
        }
    }

    private function deleteFolderID($foderID) {
        $dir = $this->params['upload_dir'] . $foderID;

        if ( (! empty($foderID)) && (is_dir($dir)) ) {
            MyHelpers::getInstance()->deleteFolder($dir);
            return TRUE;
        }
        else
            return FALSE;
    }
    /*-------------------------------------------------------------------------
     PROCESSING FILE
     ------------------------------------------------------------------------*/
    /*-------------------------------------------------------------------------
     SORT HELPER
     ------------------------------------------------------------------------*/
    /**
     * Hoán đổi thuộc tính sort_order của 2 record có ID tương ứng
     * @param integer $pk1
     * @param integer $pk2 
     */
    public function swapSortOrder($pk1, $pk2) {
        $record_1    = $this->findByPk($pk1);
        $sortOrder_1 = $record_1->getAttribute('sort_order');

        $record_2    = $this->findByPk($pk2);
        $sortOrder_2 = $record_2->getAttribute('sort_order');

        //update
        $record_1->sort_order = $sortOrder_2;
        $record_1->save();

        $record_2->sort_order = $sortOrder_1;
        $record_2->save();
    }

    /**
     * Lấy Record của trang liền sau
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetLesser($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage + 1) * $pageSize;
        $command->limit(1, $offset);
        $row    = $command->queryScalar($criteria->params);

        return $row;
    }

    /**
     * Lấy Record của trang liền trước
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetGreater($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage - 1) * $pageSize + ($pageSize - 1);
        $command->limit(1, $offset);

        $row = $command->queryRow(true, $criteria->params);

        return $row['id'];
    }

    /**
     * Đưa record có $pk1 lên đầu (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeTop($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order ASC'
            ));
        $criteria->compare('sort_order', '>=' . $record1->sort_order);
        $criteria->compare('sort_order', '<=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Đưa record có $pk1 xuống dưới cùng (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeBottom($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
            'order' => 'sort_order DESC'
        ));
        $criteria->compare('sort_order', '<=' . $record1->sort_order);
        $criteria->compare('sort_order', '>=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Get data from $criteria into $command
     * @param type $criteria
     * @param type $command 
     */
    private function sortFillCommand($criteria, $command) {
        $command->select('T.id AS id')->from('product_shop T');
        $command->leftJoin(
            'newsletter_type rtype', 'rtype.id = T.type_id'
        );

        if ($criteria->condition != '')
            $command->where($criteria->condition);
        if ($criteria->order != '')
            $command->order($criteria->order);
    }
    /*-------------------------------------------------------------------------
     SORT HELPER
     ------------------------------------------------------------------------*/
    
    public function clearSession($scenario='') {
        unset($_SESSION['elfinder']);
        unset($_SESSION['file_manager']);
        Yii::app()->user->setState('DProductShop', null);
        
        if ($scenario=='insert') {
            $this->deleteFolderID(Yii::app()->user->getState('folder_id'));
        }
        Yii::app()->user->setState('folder_id', null);
    }
}